# -*- coding: utf-8 -*-
"""
Sends mail.
"""
import smtplib
import logging

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

from mails.html_repo_formatter import HtmlFormatter

def _createhtmlmail(html, text, subject, frommail, tomail):
    """Creates a mime-message"""
  
    COMASPACE = ', ' 
    msg = MIMEMultipart('alternative')
    msg['Subject'] = subject
    msg['From'] = frommail
    msg['To'] = COMASPACE.join(tomail)
    
    part1 = MIMEText(text, 'plain') 
    part2 = MIMEText(html, 'html')

    msg.attach(part1)
    msg.attach(part2)
 
    logging.debug(msg.as_string())
    return msg


class MailSender: ##pylint: disable-msg=R0903
    """
    Sends mail.
    """
    def __init__(self, settings):
        """
        Creates the sender.
        
        settings: email settings
        """
        self._settings = settings
        
    def send_mail(self, tomail, subject, processors):
        """
        Sends email
        email: set of destination addresses
        subject: subject
        processors: list of processors to read data from 
        """
        title = self._settings.TITLE + " " + subject
        formatter = HtmlFormatter(title, processors)
        html = formatter.html_format_page()
        frommail = self._settings.FROM_MAIL
        if self._settings.DEBUG:
            title = title + ' <Should be send to ' + str(tomail) + '>'
            tomail = self._settings.DEBUG_EMAIL
        message = _createhtmlmail(html, "Read the mail as html!", title, frommail, tomail)
        server = smtplib.SMTP(self._settings.SMTP_HOST, \
                              self._settings.SMTP_PORT)
        if self._settings.SMTP_USE_TLS:
            server.ehlo()
            server.starttls()
            server.ehlo()
        if self._settings.SMTP_LOGIN <> "":
            server.login(self._settings.SMTP_LOGIN, self._settings.SMTP_PASSWORD)
        server.sendmail(frommail, tomail, message.as_string())
        server.quit()
        return html
